const router = require("express").Router();
const Data = require("./Data");
const typeData = require('../articleType/Data')
module.exports = router;

//文章列表
router.get("/", async (req, res) => {
    try {
        const data = await Data.findAll({
            where: { isdeleted: false }
        });
        res.status(200).json({
            data,
            message: '获取成功'
        })
    } catch (error) {
        console.log(error);
        res.cc(error)
    }
})
router.get('/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const data = await Data.findOne({ id })
        if (data) {
            res.status(200).json({
                data,
                message: '查询成功'
            })
        }
    } catch (error) {
        console.log(error);
        res.cc(error)
    }
})
router.post('/', async (req, res) => {
    try {
        const { title, context, typeId } = req.body;
        const type = await typeData.findOne({ id: typeId })
        if (!type) return res.cc('分类不存在')
        const resq = await Data.create({ title, context, typeId, type })
        if (resq) {
            res.status(200).json({
                data: resq,
                message: '添加成功'
            })
        }
    } catch (error) {
        console.log(error);
        res.cc(error)
    }
})
router.put('/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const { title, context, typeId } = req.body;
        const type = await typeData.findOne({ id: typeId })
        const resq = await Data.update({ title, context, typeId, type }, { where: { id } })
        const data = await Data.findOne({ id })
        if (resq) {
            res.status(200).json({
                data,
                message: '修改成功'
            })
        }
    } catch (error) {
        console.log(error)
        res.cc(error)
    }
})
router.delete('/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const resq = await Data.update({ isdeleted: true }, { where: { id } })
        if (resq) {
            res.status(200).json({
                message: '删除成功'
            })
        }
    } catch (error) {
        console.log(error);
        res.cc(error)
    }
})